package com.dfdchem.imd.kaiwu.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.dfdchem.imd.kaiwu.R;
import com.dfdchem.imd.kaiwu.manager.GlideManager;
import com.dfdchem.imd.kaiwu.model.User;
import com.dfdchem.imd.kaiwu.util.RequestUtil;
import com.dfdchem.imd.kaiwu.util.StringUtil;

import java.util.List;

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ViewHolder> {

    private final static String TAG = "ContactAdapter";
    private List<User> users;
    private Context context;

    public ContactAdapter(Context context) {
        this.context = context;
    }

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView avatar;
        public TextView user_name;
        public TextView user_phone;
        public ViewHolder(View view) {
            super(view);
            avatar = view.findViewById(R.id.avatar);
            user_name = view.findViewById(R.id.user_name);
            user_phone = view.findViewById(R.id.user_phone);
        }
    }

    @Override
    public ContactAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                        int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_contact, parent, false);

        return new ViewHolder(view);
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        User user = users.get(position);
        holder.user_name.setText(user.getUserName());
        holder.user_phone.setText(user.getPhone());

        String avatar_url = user.getAvatar();
        if (StringUtil.isEmpty(avatar_url)) {
            holder.avatar.setImageDrawable(context.getDrawable(R.drawable.ic_default_avatar));
        } else {
            // 适配内网地址
            if (avatar_url.startsWith(RequestUtil.url_file_short)) {
                avatar_url = RequestUtil.URL_BASE_API + avatar_url;
            }

            new GlideManager(context).load(holder.avatar, avatar_url);
        }
    }

    @Override
    public int getItemCount() {
        return users == null ? 0 : users.size();
    }

}
